import json
import re

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from apps.users.models import User
from django_redis import get_redis_connection

# Create your views here.

class UsernameCountView(View):
    # 用户名验证
    def get(self,request,username):
        # rules = '[a-zA-Z0-9]{5,20}'
        # if not re.match(rules,username):
        #     return JsonResponse({'code':0,'errmsg':'用户名格式错误'})
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})

class MobileCountView(View):
    # 手机号验证
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})

class RegisterView(View):
    def post(self,request):
        body_bytes = request.body
        body_dict = json.loads(body_bytes)
        print(type(body_dict),body_dict)

        username= body_dict.get('username')
        password= body_dict.get('password')
        password2= body_dict.get('password2')
        mobile = body_dict.get('mobile')
        image_code= body_dict.get('image_code')
        sms_code= body_dict.get('sms_code')
        allow= body_dict.get('allow')

        if not all([username,password,mobile]):
            return JsonResponse({'code':400,'errmsg':'缺少必要信息'})
        if not re.match(r'^[a-zA-Z0-9]{5,20}$',username):
            return JsonResponse({'code':400,'errmsg':'缺少必要信息'})
        if not re.match(r'^[a-zA-Z0-9_]{8,20}$',password):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要信息'})
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '缺少必要信息'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要信息'})
        if allow != True:
            return JsonResponse({'code': 400, 'errmsg': '缺少必要信息'})
        # 验证码验证
        redis_cli = get_redis_connection('code')
        redis_code = redis_cli.get(mobile).decode()
        if redis_code is None:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if redis_code != sms_code:
            return JsonResponse({'code':400,'errmsg':'验证码错误'})

        # 保存的密码没有加密
        # User.objects.create(username = username,password = password,mobile = mobile)
        # 保存的密码加密
        try:
            user = User.objects.create_user(
                username = username,
                password = password,
                mobile = mobile
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 保存账号,用户自动登录
        login(request,user)

        return JsonResponse({'code':0,'errmsg':'ok'})













